//
//  OrderDetailsViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/26.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
class OrderDetailsViewController: BaseViewController {

    @IBOutlet var addTaskBtn: UIButton!
    
    @IBOutlet var editLabel: UILabel!
    
    @IBOutlet var orderDetailTableview: UITableView!
    let ordeDetailsCell = "orderDetailsCell"
    var ordermodel:OrderModel?
    var tasks:[TaskModel]?
    var orderStatus:Int?
    
    
    @IBOutlet var orderNumLabel: UILabel!
    
    @IBOutlet var userHeaderImageview: UIImageView!
    
    @IBOutlet var serviceTypeLabel: UILabel!
    
    @IBOutlet var remarksLabel: UILabel!
    
    @IBOutlet var userNameLabel: UILabel!
    
    @IBOutlet var carNumLabel: UILabel!
    
    @IBOutlet var userPhoneLabel: UILabel!
    
    @IBOutlet var downTimeLabel: UILabel!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requstTaskList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configView()
        renderViewEvents()
    }
    
    func configView() -> Void {
        orderDetailTableview.delegate = self
        orderDetailTableview.dataSource = self
        orderDetailTableview.separatorStyle = .none
        orderDetailTableview.showsVerticalScrollIndicator = false
        orderDetailTableview.register(UINib(nibName: "OrderDetailsTableViewCell", bundle: nil), forCellReuseIdentifier: ordeDetailsCell)
    }
    
    func renderViewEvents() -> Void {
        orderNumLabel.text = "订单编号：" + (ordermodel?.ordersn)!;
        userNameLabel.text = "姓名：" + (ordermodel?.username)!
        userPhoneLabel.text = "电话：" + (ordermodel?.phone)!
        remarksLabel.text = "备注：" + (ordermodel?.description)!
        if ((ordermodel?.server) != nil){
            serviceTypeLabel.text = "服务类型：" + (ordermodel?.server?.name)!
        }
        downTimeLabel.text = "下单时间：" + (ordermodel?.addtime)!
        carNumLabel.text = "车牌号：" + (ordermodel?.car)!
        switch self.orderStatus {
        case 0:
        addTaskBtn.isHidden = false
        editLabel.isHidden = false
        default:
        addTaskBtn.isHidden = true
        editLabel.isHidden = true
        }
    }
    
    @IBAction func addTaskBtnPress(_ sender: UIButton) {//新增服务
        let addTaskVC = OrderAddTaskViewController()
        addTaskVC.title = "添加任务分配"
        addTaskVC.orderId = (ordermodel?.id)!
        self.navigationController?.pushViewController(addTaskVC, animated: true)
        
    }
    
    
    //网络请求
    //请求任务列表
    func requstTaskList() -> Void {
        
        Alamofire.request(taskListUrl, method:.post, parameters: ["orderid":ordermodel?.id ?? String(),"shopid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in

                switch response.result.isSuccess {
                case true:

                    var basemodel = BaseResponseOfModel<BaseArrayData<TaskModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!

                    switch basemodel.status! {
                    case true:
                    self.tasks = basemodel.data?.data
                    self.orderDetailTableview.reloadData()

                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    
    //删除任务
    func requestDeleteTask (Id:String) -> Void {
        
        
        Alamofire.request(deleteTaskUrl, method:.post, parameters:["id":Id])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        print("删除成功")
                        self.requstTaskList()
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension OrderDetailsViewController: UITableViewDelegate,UITableViewDataSource {
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tasks?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ordeDetailsCell, for: indexPath) as! OrderDetailsTableViewCell
        cell.selectionStyle = .none
        let model = self.tasks![indexPath.item];
        cell.serviceLabel.text = model.content
        cell.excutorexLabel.text = model.member?.name
        cell.executionTimeLabel.text = model.addtime
        cell.remarksLabel.text = model.description
        cell.upLineView.isHidden = false
        cell.downLineView.isHidden = false
        if (indexPath.item == 0) {
            cell.upLineView.isHidden = true
            if (self.tasks?.count == 1){
                cell.downLineView.isHidden = true
            }
        }else if (indexPath.item == (self.tasks?.count)! - 1){
            cell.downLineView.isHidden = true
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //        if selectedNumber == 1 {
        //            return 115
        //        }else {
        //            return 185
        //        }
        return ScaleHeight(88)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.tasks![indexPath.item];
        if (self.orderStatus == 0) {
            let editOrdeleteView = EditOrDeleteView.getEditOrDeletePopView()
            editOrdeleteView.callBackBlock { (intvalue) in
                switch intvalue {
                case 0:
                    //编辑
                    let editTaskVC = OrderAddTaskViewController()
                    editTaskVC.title = "编辑任务分配"
                    editTaskVC.taskId = model.id
                    editTaskVC.serviceType = model.content
                self.navigationController?.pushViewController(editTaskVC, animated: true)
                    bgWindow?.hidBackgroundWindow()
                case 1:
                    //删除
                    self.requestDeleteTask(Id: model.id)
                    bgWindow?.hidBackgroundWindow()
                default:
                    break
                }
            }
            bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
            bgWindow?.shake(toShow: editOrdeleteView)
        }
    }
       
}

